import pymysql

class MyORM:
    def __init__(self):
        # 建立与数据库的连接
        conn = pymysql.connect(
            host="192.168.1.129",
            port=3306,
            user="admin1",
            password="123",
            database="mumushouji",
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor,
            autocommit=True
        )
        # 实例化一个游标对象
        cursor = conn.cursor()
        self.cursor = cursor

    def execute(self,sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()

class User:
    table_name = "user"

    # def query_one(self,select_params,where_params):
    #     sql = "select %s from %s where %s limit 1" % (select_params,self.table_name,where_params)
    #     return MyORM().execute(sql)

    def query_one(self,select_params=None,**where_params):
        # sql = "select %s from %s where %s limit 1" % (select_params, self.table_name, where_params)

        # select username,nickname from user
        if select_params is not None and type(select_params) is list:
            # 进行sql语句的拼接
            sql = "select "
            for i in select_params:
                sql += i+","
            sql = sql[0:-1]
            sql = sql + " from " + self.table_name
            print(sql)
        else:
            sql = "select * from " + self.table_name

        # select username,nickname from user where user_id=3 and username='3@qq.com'
        print(where_params)
        if where_params is not None:
            sql = sql + " where "
            for k,v in where_params.items():
                sql += " %s='%s' and" % (k,v)
            sql += ' 1=1 limit 1'
            print(sql)
        # return 0
        return MyORM().execute(sql)


if __name__ == "__main__":
    user = User()
    # print(user.query_one("username,nickname","user_id=3"))
    # print(user.query_one(["username","nickname"]))
    # print(user.query_one())
    # print(user.query_one(["username","nickname"],{"user_id":3,}))
    # print(user.query_one(["username","nickname","password"],user_id=3))
    print(user.query_one())
